﻿#include "cmodbusunitcoil.h"

CModbusUnitCoil::CModbusUnitCoil(ESigType maptype, QObject *parent)
    : CModbusUnitBase(3,maptype,parent)
{
    QMap<int, QString> vmap;
    vmap.insert(0, "线圈");
    vmap.insert(1, "离散输入");
    m_fieldValueMap.insert("寄存器类型", vmap);
    vmap.clear();

    vmap.insert(0, "否");
    vmap.insert(1, "是");
    m_fieldValueMap.insert("是否bit", vmap);
}

QString CModbusUnitCoil::getFieldNameByCol(int col) {
    if(col < EInvalid)
        return CModbusUnitBase::getFieldNameByCol(col);

    if(5 == col) {
        return "是否bit";
    } else if(6 == col) {
        return "bit偏移";
    } else if(7 == col) {
        return "bit数量";
    }
    return "";
}

QVariant CModbusUnitCoil::getFieldValueByFielddName(const QString &name) {
    if("是否bit" == name) {
        return isbit ? 1 : 0;
    } else if("bit偏移" == name) {
        return bit_offest;
    } else if("bit数量" == name) {
        return bit_num;
    } else {
        return CModbusUnitBase::getFieldValueByFielddName(name);
    }
}

void CModbusUnitCoil::setFieldValueByCol(int col, const QVariant &value) {
    if(5 == col) {
        isbit = value.toInt() == 0 ? false : true;
        changeBgColor(true);
    } else if(6 == col) {
        bit_offest = value.toInt();
        changeBgColor(true);
    } else if(7 == col) {
        bit_num = value.toInt();
        changeBgColor(true);
    } else {
        CModbusUnitBase::setFieldValueByCol(col, value);
    }
}

QJsonObject CModbusUnitCoil::toJson()
{
    QJsonObject obj = CModbusUnitBase::toJson();
    obj["is_bit"] = isbit;
    obj["bit_offest"] = bit_offest;
    obj["bit_num"] = bit_num;
    return obj;
}

void CModbusUnitCoil::fromJson(const QJsonObject &obj) {
    CModbusUnitBase::fromJson(obj);
    isbit = obj["is_bit"].toBool();
    bit_offest = obj["bit_offest"].toInt();
    bit_num = obj["bit_num"].toInt();
    if(!is_init)
        deleteReset();
}

QSharedPointer<IModel> CModbusUnitCoil::createEmpty()
{

}

void CModbusUnitCoil::changeBgColor(bool ischange) {
    if(!ischange) {
        m_backgroundField.clear();
        m_ischange = false;
    } else {
        m_backgroundField.insert("是否bit", "#FFA49F");
        m_backgroundField.insert("bit偏移", "#FFA49F");
        m_backgroundField.insert("bit数量", "#FFA49F");
        m_ischange = true;
    }
    CModbusUnitBase::changeBgColor(ischange);
}

bool CModbusUnitCoil::checkData() {
    if(isbit) {
        if(bit_offest < 0 || bit_num < 1) {
            return false;
        }
    }
    return CModbusUnitBase::checkData();
}

void CModbusUnitCoil::deleteReset() {
    changeBgColor(false);
    isbit = false;
    bit_offest = -1;
    bit_num = -1;
    reg_type = 0;
    CModbusUnitBase::deleteReset();
    m_backgroundField.insert("是否bit", "#6B6B6B");
    m_backgroundField.insert("bit偏移", "#6B6B6B");
    m_backgroundField.insert("bit数量", "#6B6B6B");
}
